package com.weijian.controller.admin;


import com.weijian.common.BaseContext;
import com.weijian.common.exception.ServiceException;
import com.weijian.dal.entity.Address;
import com.weijian.service.AddressService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/addresses")
@RequiredArgsConstructor
@Slf4j
public class AddressController {

    private final AddressService addressService;

    @Operation(summary = "根据id查询地址")
    @GetMapping("{addressId}")
    public Address findAddressById(@PathVariable("addressId") Long id) {
        // 1.根据id查询
        Address address = addressService.getById(id);
        //2.判断当前用户
        Long userId = BaseContext.getCurrentId();
        log.info( "当前用户id:{}", userId);
        if (!address.getUserId().equals(userId)) {
            throw new ServiceException(401, "地址不属于当前登录用户");
        }
        return address;
    }

    @Operation(summary = "新增地址")
    @PostMapping
    public void save(@RequestBody Address address) {
        address.setUserId(BaseContext.getCurrentId());
        log.info("新增地址:{}", address);
        addressService.save(address);
    }

    @Operation(summary = "更细地址")
    @PutMapping("/update")
    public void updateAddress(@RequestBody Address address) {
        addressService.updateById(address);
    }

    @Operation(summary = "设置为默认地址")
    @PutMapping("/default")
    public void SetDefaultAddress() {
        Address address = new Address();
        address.setIsDefault(1);
        addressService.updateById(address);
    }

    @Operation(summary = "根据id删除地址")
    @DeleteMapping("/delete")
    public void deleteAddressById(@RequestParam("id") Long id) {
        addressService.removeById(id);
    }


    @Operation(summary = "查询当前用户地址列表")
    @GetMapping
    public List<Address> findMyAddresses() {
        return addressService.findMyAddresses();
    }
}
